<template>
  <el-form
    ref="form"
    :model="userForm"
    :rules="rules"
    label-width="80px"
  >
    <el-form-item label="用户名">
      <el-input v-model="userForm.username" disabled />
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model="userForm.name" placeholder="请输入姓名" />
    </el-form-item>
    <el-form-item label="邮箱" prop="email">
      <el-input v-model="userForm.email" placeholder="请输入邮箱" />
    </el-form-item>
    <el-form-item label="手机号" prop="phone">
      <el-input v-model="userForm.phone" placeholder="请输入手机号" />
    </el-form-item>
    <el-form-item label="部门" prop="department">
      <el-input v-model="userForm.department" placeholder="请输入部门" />
    </el-form-item>
    <el-form-item label="职位" prop="position">
      <el-input v-model="userForm.position" placeholder="请输入职位" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { updateProfile } from '@/api/user'

export default {
  name: 'UserInfo',
  props: {
    user: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      userForm: {
        id: undefined,
        username: '',
        name: '',
        email: '',
        phone: '',
        department: '',
        position: ''
      },
      rules: {
        name: [
          { required: true, message: '姓名不能为空', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    user: {
      handler(val) {
        if (val) {
          this.userForm = {
            id: val.id,
            username: val.username,
            name: val.name,
            email: val.email,
            phone: val.phone,
            department: val.department,
            position: val.position
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    submit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updateProfile(this.userForm).then(() => {
            this.$message.success('个人信息修改成功')
            this.$emit('updateProfile')
          })
        }
      })
    },
    cancel() {
      this.reset()
    },
    reset() {
      if (this.user) {
        this.userForm = {
          id: this.user.id,
          username: this.user.username,
          name: this.user.name,
          email: this.user.email,
          phone: this.user.phone,
          department: this.user.department,
          position: this.user.position
        }
      }
    }
  }
}
</script> 